﻿# -*- coding:utf-8 -*-
"""

"""

from datetime import datetime
#from StringIO import StringIO

from django import forms

from pcadmin.models import Plugin, Agent, Task, AgentLog, TaskField, TaskFieldValue, TaskQueue
from pcadmin.widgets import CalendarDateTimeInput


class CreateTaskQueueForm(forms.ModelForm):

    class Meta:
        model = TaskQueue
        exclude = ('user', 'task', 'agent', 'acknowledge', 'done',)
        widgets = {
            'start': CalendarDateTimeInput(),
        }        


    def __init__(self, task, *args, **kwargs):
        """
        Add any custom fields that are defined to the form
        """
        super(CreateTaskQueueForm, self).__init__(*args, **kwargs)
        self.task = task
        for field in TaskField.objects.filter(task = self.task):
            instanceargs = {
                    'label': field.label,
                    'help_text': field.help_text,
                    'required': field.required,
                    }
            if field.data_type == 'varchar':
                fieldclass = forms.CharField
                instanceargs['max_length'] = field.max_length
            elif field.data_type == 'text':
                fieldclass = forms.CharField
                instanceargs['widget'] = forms.Textarea
                instanceargs['max_length'] = field.max_length
            elif field.data_type == 'integer':
                fieldclass = forms.IntegerField
            elif field.data_type == 'decimal':
                fieldclass = forms.DecimalField
                instanceargs['decimal_places'] = field.decimal_places
                instanceargs['max_digits'] = field.max_length
            elif field.data_type == 'list':
                fieldclass = forms.ChoiceField
                choices = field.choices_as_array
                if field.empty_selection_list:
                    choices.insert(0, ('','---------' ) )
                instanceargs['choices'] = choices
            elif field.data_type == 'boolean':
                fieldclass = forms.BooleanField
            elif field.data_type == 'date':
                fieldclass = forms.DateField
                instanceargs['widget'] = extras.SelectDateWidget
            elif field.data_type == 'time':
                fieldclass = forms.TimeField
            elif field.data_type == 'datetime':
                fieldclass = forms.DateTimeField
            elif field.data_type == 'email':
                fieldclass = forms.EmailField
            elif field.data_type == 'url':
                fieldclass = forms.URLField
            elif field.data_type == 'ipaddress':
                fieldclass = forms.IPAddressField
            elif field.data_type == 'slug':
                fieldclass = forms.SlugField
            elif field.data_type == 'file':
                fieldclass = forms.FileField                    
            
            self.fields['custom_%s' % field.name] = fieldclass(**instanceargs)


    def save(self, agent, user):
        """
        Writes and returns a TaskQueue() object
        """
        taskqueue =  TaskQueue( task = self.task,
                                start  = self.cleaned_data['start'],
                                agent = agent, 
                                acknowledge = False,
                                done = False,
                                user = user                            
                            )

        taskqueue.save()
        for field, value in self.cleaned_data.items():
            if field.startswith('custom_'):
                field_name = field.replace('custom_', '')
                taskfield = TaskField.objects.get(name=field_name)
                cfv = TaskFieldValue(taskqueue=taskqueue,
                            taskfield=taskfield,
                            value=value)
                cfv.save()
        return taskqueue
